package com.jee.ssm.common.utils.wechat;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import com.alibaba.fastjson.JSONObject;
import com.jee.ssm.model.json.Tip;

public class WXPay{
	
	@SuppressWarnings("unchecked")
	public Tip payByApp(Unifiedorder unifiedorder, PaymaxConfig config){
		Tip tip = new Tip();
		//参数：开始生成签名
		SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
		parameters.put("appid", unifiedorder.getAppid());
		parameters.put("mch_id", unifiedorder.getMch_id());
		parameters.put("nonce_str", unifiedorder.getNonce_str());
		parameters.put("body", unifiedorder.getBody());
		parameters.put("detail", unifiedorder.getDetail());
		parameters.put("attach", unifiedorder.getAttach());
		parameters.put("out_trade_no", unifiedorder.getOut_trade_no());
		parameters.put("total_fee", String.valueOf(unifiedorder.getTotal_fee()));
		parameters.put("time_start", unifiedorder.getTime_start());
		parameters.put("time_expire", unifiedorder.getTime_expire());
		parameters.put("notify_url", unifiedorder.getNotify_url());
		parameters.put("trade_type", unifiedorder.getTrade_type());
		parameters.put("spbill_create_ip", unifiedorder.getSpbill_create_ip());
		//第一次签名
		String sign = WXSignUtils.createSign("UTF-8", parameters, config.getKey());
		unifiedorder.setSign(sign);
		try{
			//第一次请求微信服务器。请求prepay_id（预下单）
			String weixinPost = HttpXmlUtils.httpsRequest(config.getUrl(), config.getMethod(), HttpXmlUtils.xmlInfo(unifiedorder)).toString();			
			Map<String, String> restmap = XMLUtil.doXMLParse(weixinPost);
			SortedMap<Object, Object> payMap = new TreeMap<Object, Object>();
	        if ("SUCCESS".equals(restmap.get("result_code"))) {
	            payMap.put("appid", restmap.get("appid"));
	            payMap.put("partnerid", restmap.get("mch_id"));
	            payMap.put("prepayid", restmap.get("prepay_id"));
	            payMap.put("package", "Sign=WXPay");
	            payMap.put("noncestr", restmap.get("nonce_str"));
	            payMap.put("timestamp", payTimestamp());
	            //请求到prepay_id后，进行新参数二次签名；
	            payMap.put("sign", WXSignUtils.createSign("UTF-8", payMap, config.getKey()));
	            payMap.put("packageValue", payMap.get("package"));
	            payMap.remove("package");
	            tip = new Tip(payMap);
	        } else {
	        	tip = new Tip(1, "二次签名出现异常");
	        }
		} catch(Exception e) {
			tip = new Tip(2, "微信支付请求支付对象异常");
		}
		
		//签名完成后直接把信息给前端，前端用payjson去调起微信
//        JSONObject payjson = maptojson(payMap);
//        System.out.println(payjson);
		return tip;
	}
	
	@SuppressWarnings("unchecked")
	public Tip payByCode(Unifiedorder unifiedorder, PaymaxConfig config) {
		Tip tip = new Tip();
		//参数：开始生成签名
		SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
		parameters.put("appid", unifiedorder.getAppid());
		parameters.put("mch_id", unifiedorder.getMch_id());
		parameters.put("nonce_str", unifiedorder.getNonce_str());
		parameters.put("body", unifiedorder.getBody());
		parameters.put("detail", unifiedorder.getDetail());
		parameters.put("attach", unifiedorder.getAttach());
		parameters.put("out_trade_no", unifiedorder.getOut_trade_no());
		parameters.put("total_fee", String.valueOf(unifiedorder.getTotal_fee()));
		parameters.put("time_start", unifiedorder.getTime_start());
		parameters.put("time_expire", unifiedorder.getTime_expire());
		parameters.put("notify_url", unifiedorder.getNotify_url());
		parameters.put("trade_type", unifiedorder.getTrade_type());
		parameters.put("spbill_create_ip", unifiedorder.getSpbill_create_ip());
		//第一次签名
		String sign = WXSignUtils.createSign("UTF-8", parameters, config.getKey());
		unifiedorder.setSign(sign);
		try{
			//第一次请求微信服务器。请求prepay_id（预下单）
			String weixinPost = HttpXmlUtils.httpsRequest(config.getUrl(), config.getMethod(), HttpXmlUtils.xmlInfo(unifiedorder)).toString();			
			Map<String, String> restmap = XMLUtil.doXMLParse(weixinPost);
	        if ("SUCCESS".equals(restmap.get("result_code"))) {
	            tip = new Tip(restmap.get("code_url"));
	        } else {
	        	tip = new Tip(1, "二次签名出现异常");
	        }
		} catch(Exception e) {
			tip = new Tip(2, "微信支付请求支付对象异常");
		}
		
		return tip;
	}
	
	@SuppressWarnings("unchecked")
	public Tip payByProgramApp(Unifiedorder unifiedorder, PaymaxConfig config){
		Tip tip = new Tip();
		//参数：开始生成签名
		SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
		parameters.put("appid", unifiedorder.getAppid());
		parameters.put("mch_id", unifiedorder.getMch_id());
		parameters.put("nonce_str", unifiedorder.getNonce_str());
		parameters.put("body", unifiedorder.getBody());
		parameters.put("detail", unifiedorder.getDetail());
		parameters.put("attach", unifiedorder.getAttach());
		parameters.put("out_trade_no", unifiedorder.getOut_trade_no());
		parameters.put("total_fee", String.valueOf(unifiedorder.getTotal_fee()));
		parameters.put("time_start", unifiedorder.getTime_start());
		parameters.put("time_expire", unifiedorder.getTime_expire());
		parameters.put("notify_url", unifiedorder.getNotify_url());
		parameters.put("trade_type", unifiedorder.getTrade_type());
		parameters.put("spbill_create_ip", unifiedorder.getSpbill_create_ip());
		parameters.put("openid", unifiedorder.getOpenid());
		//第一次签名
		String sign = WXSignUtils.createSign("UTF-8", parameters, config.getKey());
		unifiedorder.setSign(sign);
		try{
			//第一次请求微信服务器。请求prepay_id（预下单）
			String weixinPost = HttpXmlUtils.httpsRequest(config.getUrl(), config.getMethod(), HttpXmlUtils.xmlInfo(unifiedorder)).toString();			
			Map<String, String> restmap = XMLUtil.doXMLParse(weixinPost);
			SortedMap<Object, Object> payMap = new TreeMap<Object, Object>();
	        if ("SUCCESS".equals(restmap.get("result_code"))) {
	            payMap.put("appId", restmap.get("appid"));
	            payMap.put("nonceStr", restmap.get("nonce_str"));
	            payMap.put("package", "prepay_id=" + restmap.get("prepay_id"));
				payMap.put("signType", "MD5");
	            payMap.put("timeStamp", payTimestamp());
	            //请求到prepay_id后，进行新参数二次签名；
	            payMap.put("sign", WXSignUtils.createSign("UTF-8", payMap, config.getKey()));
	            payMap.put("packageValue", payMap.get("package"));
	            payMap.remove("package");
	            tip = new Tip(payMap);
	        } else {
	        	tip = new Tip(1, "二次签名出现异常");
	        }
		} catch(Exception e) {
			tip = new Tip(2, "微信支付请求支付对象异常");
		}
		
		//签名完成后直接把信息给前端，前端用payjson去调起微信
//        JSONObject payjson = maptojson(payMap);
//        System.out.println(payjson);
		return tip;
	}
	
	/**
	 * 获取时间戳
	 */
    public static String payTimestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
    
    /**
     * 将Map转成json方便前端解析
     */
    public static JSONObject maptojson(Map<String, String> map) {
    	JSONObject json = new JSONObject();
    	for (Object key : map.keySet()) {
			json.put((String) key, map.get(key));
		}
    	return json;
    }
    
}
